package controllers

import (
	"encoding/json"
	"errors"
	"github.com/astaxie/beego"
	"qysoft/libs/encrypt"
	"qysoft/models"
	"strings"
	"time"
)

// AssetsbuyController operations for Assetsbuy
type AssetsbuyController struct {
	CommonController
}

// URLMapping ...
func (c *AssetsbuyController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetDoing", c.GetDoing)
	c.Mapping("GetCompleted", c.GetCompleted)
	c.Mapping("GetFinish", c.GetFinish)
	c.Mapping("Apply", c.Apply)

}

// Post ...
// @Title Post
// @Description create Assetsbuy
// @Param	body		body 	models.Assetsbuy	true		"body for Assetsbuy content"
// @Success 201 {int} models.Assetsbuy
// @Failure 403 body is empty
// @router / [post]
func (c *AssetsbuyController) Post() {
	var v models.Assetsbuy
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	if err := json.Unmarshal(rdata, &v); err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Status = 1
	v.Isdelete = 0

	// vtype, _ := sdata["Type"].(string)
	// v.Type, _ = strconv.Atoi(vtype)
	v.Id = encrypt.GetGuid()
	_, err = models.AddAssetsbuy(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)

	}
	flow, err := models.GetFlowByName("采购单")
	ts, err := models.InitFSM(user, flow.Id, "Assetsbuy", v.Id)
	beego.Debug("ts err: ", ts)
	// fsm := models.GetFSM(ts)
	// // beego.Debug("fsm err: ", fsm)
	// ev, _ := models.GetEventByName("上报")
	// err = fsm.Trigger(ts.Currentstate, ev.Id, ts)
	// if err != nil {
	// 	beego.Error("trigger err: ", err)
	// }
	c.Dlog("添加了采购单", v.Id)
	c.RetSuccess(v.Id)

}

// Apply ...
// @Title Apply
// @Description 申请上报
// @Param	body		body 	models.Assetsbuy	true		"body for Assetsbuy content"
// @Success 201 {int} models.Assetsbuy
// @Failure 403 body is empty
// @router /Apply [post]
func (c *AssetsbuyController) Apply() {
	user := c.User
	beego.Debug(c.GetString("tdata"))
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrNoData)
	}
	sdata, _ := rdata.(map[string]interface{})
	beego.Debug(sdata)
	busyid := sdata["Id"].(string)

	ts, err := models.GetFlowinstanceByBusyId(busyid)
	// 针对退回的单据重新生成流程实例
	if ts.Status == 3 {
		models.ReApply(user.Id, busyid, ts)
		flow, _ := models.GetFlowByName("采购单")
		ts, _ = models.InitFSM(user, flow.Id, "Assetsbuy", busyid)
	}
	beego.Debug("ts err: ", ts)
	fsm := models.GetFSM(ts)
	// beego.Debug("fsm err: ", fsm)
	ev, _ := models.GetEventByName("上报")
	err = fsm.Trigger(ts.Currentstate, ev.Id, ts)
	if err != nil {
		beego.Error("trigger err: ", err)
		c.RetError(ErrPermission)
	}
	c.Dlog("上报了采购单", busyid)
	c.RetSuccess(busyid)

}

// GetOne ...
// @Title Get One
// @Description get Assetsbuy by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Assetsbuy
// @Failure 403 :id is empty
// @router /:id [get]
func (c *AssetsbuyController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetAssetsbuyById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get Assetsbuy
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Assetsbuy
// @Failure 403
// @router / [get]
func (c *AssetsbuyController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	query["Isdelete"] = "0"
	l, err := models.GetAllAssetsbuy(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// Update ...
// @Title Put
// @Description update the Assetsbuy
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Assetsbuy	true		"body for Assetsbuy content"
// @Success 200 {object} models.Assetsbuy
// @Failure 403 :id is not int
// @router /Update [post]
func (c *AssetsbuyController) Update() {
	var v models.Assetsbuy
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	if err := json.Unmarshal(rdata, &v); err != nil {
		beego.Error(err)
		c.RetError(ErrInputData)
	}
	v.Updater = user.Name
	v.Utime = time.Now()
	v.Status = 1
	v.Isdelete = 0
	err = models.UpdateAssetsbuy(&v)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("修改了采购单,采购单id为：", v.Id, 1, &v)
	c.RetSuccess(v.Id)
}

// Delete ...
// @Title Delete
// @Description delete the Assetsbuy
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *AssetsbuyController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	query := map[string]interface{}{
		"Id": id,
	}
	err = models.SoftDeleteObject("Assetsbuy", query, user.Name)
	if err != nil {
		beego.Error(err)
		c.RetError(ErrDatabase)
	}
	c.Dlog("删除了采购单", id)
	c.RetSuccess(id)
}

// GetDoing ...
// @Title GetDoing
// @Description get Assetsbuy by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Assetsbuy
// @Failure 403  empty
// @router /GetDoing [get]
func (c *AssetsbuyController) GetDoing() {
	user := c.User
	v, err := models.GetBusyDoing(user.Id, "Assetsbuy")
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetCompleted ...
// @Title GetCompleted
// @Description get Assetsbuy by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Assetsbuy
// @Failure 403 :id is empty
// @router /GetCompleted [get]
func (c *AssetsbuyController) GetCompleted() {
	user := c.User
	v, err := models.GetBusyFlowing(user.Id, "Assetsbuy")
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetFinish ...
// @Title GetFinish
// @Description get Assetsbuy by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Assetsbuy
// @Failure 403 GetFinish is empty
// @router /GetFinish [get]
func (c *AssetsbuyController) GetFinish() {
	user := c.User
	v, err := models.GetBusyFinish(user.Id, "Assetsbuy")
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}
